<?php

namespace plugin\admin\app\controller;

use app\services\PropertyService;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use support\Db;
use support\Request;
use support\Response;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 团队日志 
 */
class UserPropertyLogController extends Crud
{
    
    /**
     * @var UserPropertyLog
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserPropertyLog;
    }

    public function reduce(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');

            $log = UserPropertyLog::where('id', $id)->first();

            if ($log['is_reduce']) {
                throw new \Exception('该项已扣除');
            }

            $log->is_reduce = 1;
            $log->save();

            PropertyService::reduce($log['user_id'], $log['type'], $log['amount'], UserPropertyLog::REWARD_INTEGRAL_REDUCE, $log['id']);

            Db::commit();
            return $this->json(0, '成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->json(400, $e->getMessage());
        }
    }

    public function select(Request $request): Response
    {
        $showType = $request->get('show_type', 'only_order_no');
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order, $showType);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order= 'desc', string $showType = 'only_order_no')
    {
        $model = $this->model;

        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                }elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }

        if ($showType == 'only_order_no') {
            $model = $model->whereNotNull('order_no')->where('order_no', '<>', '');
        }

        return $model;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('user-property-log/index');
    }

    public function all(): Response
    {
        return view('user-property-log/all', [
            'types' => UserPropertyLog::TYPE_TEXT
        ]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('user-property-log/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('user-property-log/update');
    }

    protected function formatNormal($items, $total): Response
    {
        $orderNos = array_column($items, 'order_no');
        $orders = Order::whereIn('order_no', $orderNos)->get()->toArray();
        $orders = array_combine(
            array_column($orders, 'order_no'),
            array_values($orders)
        );

        $userIds = array_column($items, 'user_id');
        $orderUserIds = array_column($orders, 'user_id');

        $allUserIds = array_merge($userIds, $orderUserIds);

        $users = User::whereIn('id', $allUserIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'id'),
            array_values($users)
        );

        $levels = UserLevel::list();
        $levels = array_combine(
            array_column($levels, 'value'),
            array_column($levels, 'name')
        );

        foreach ($items as $key=>$item) {
            $order = $orders[$item['order_no']] ?? ['user_id' => 0];

            $items[$key]['type_text'] = UserPropertyLog::getTypeText($item['type']);
            $items[$key]['source_text'] = UserPropertyLog::getSourceText($item['source']);
            $items[$key]['order'] = $order;
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
